package logic

import (
	"context"
	"errors"

	"test-api/internal/model"
	"test-api/internal/svc"
	"test-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserListLogic {
	return &UserListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserListLogic) UserList(req *types.STUserListReq) (resp *types.STUserListRsp, err error) {
	resp = &types.STUserListRsp{
		Items: []*types.User{},
	}

	if req.Page == 0 {
		req.Page = 1
	}
	if req.Limit == 0 {
		req.Limit = 20
	}

	db := l.svcCtx.DB.Model(&model.User{}).Where("state = 1")

	if err = db.Count(&resp.Total).Error; err != nil {
		return resp, errors.New("数据库错误")
	}

	if resp.Total == 0 {
		return resp, nil
	}

	db = db.Order("id desc").Offset(int((req.Page - 1) * req.Limit)).Limit(int(req.Limit))

	if err = db.Find(&resp.Items).Error; err != nil {
		return resp, errors.New("数据库错误")
	}

	return
}
